package com;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestWeek2 {

	public static void main(String[] args) {
//		System.out.println(TestWeek2.getweek("2020-11-09"));
		Calendar cal = Calendar.getInstance();
//		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+3, 1);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // 设置时间格式
		System.out.println(sdf.format(cal.getTime()));
		
	}

	/** java 获取月周 */
	public static Integer getweek(String mydata) {

		Integer week = null;
		try {

			Calendar calendar = Calendar.getInstance();
			calendar.setFirstDayOfWeek(Calendar.MONDAY);

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
			Calendar cal = Calendar.getInstance();
			Date time = sdf.parse(mydata);
			cal.setTime(time);

			// 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
			int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
			if (1 == dayWeek) {
				cal.add(Calendar.DAY_OF_MONTH, -1);
			}
			cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
			int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
			cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
			System.out.println("所在周星期一的日期：" + sdf.format(cal.getTime()));

			String date1 = sdf.format(cal.getTime());
			Date time1 = sdf.parse(date1);
			calendar.setTime(time1);
			int week1 = calendar.get(Calendar.WEEK_OF_YEAR);

			System.out.println(cal.getFirstDayOfWeek() + "-" + day + "+6=" + (cal.getFirstDayOfWeek() - day + 6));

			cal.add(Calendar.DATE, 6);
			System.out.println("所在周星期日的日期：" + sdf.format(cal.getTime()));

			String date2 = sdf.format(cal.getTime());
			Date time2 = sdf.parse(date2);
			calendar.setTime(time2);
			int week2 = calendar.get(Calendar.WEEK_OF_YEAR);

			week = (week1 >= week2 ? week2 : week1);

		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return week;
	}

}
